const app = getApp()

Page({
  data: {
    banners: [
      {
        id: 1,
        imageUrl: '/images/banner1.jpg'
      },
      {
        id: 2,
        imageUrl: '/images/banner2.jpg'
      },
      {
        id: 3,
        imageUrl: '/images/banner3.jpg'
      }
    ],
    categories: [
      {
        id: 1,
        name: '自然风光',
        icon: '/images/nature.png'
      },
      {
        id: 2,
        name: '人文古迹',
        icon: '/images/culture.png'
      },
      {
        id: 3,
        name: '主题乐园',
        icon: '/images/theme.png'
      },
      {
        id: 4,
        name: '美食购物',
        icon: '/images/food.png'
      },
      {
        id: 5,
        name: '更多',
        icon: '/images/more.png'
      }
    ],
    spots: [
      {
        id: 1,
        name: '西湖',
        description: '杭州西湖，中国十大风景名胜之一，以秀丽的湖光山色和众多的人文古迹闻名于世。',
        imageUrl: '/images/spots/xihu.jpg',
        price: 0,
        rating: 4.8,
        category: 1
      },
      {
        id: 2,
        name: '故宫',
        description: '北京故宫，世界上现存规模最大、保存最为完整的木质结构古建筑之一。',
        imageUrl: '/images/spots/gugong.jpg',
        price: 60,
        rating: 4.9,
        category: 2
      },
      {
        id: 3,
        name: '黄山',
        description: '安徽黄山，以奇松、怪石、云海、温泉"四绝"著称于世。',
        imageUrl: '/images/spots/huangshan.jpg',
        price: 230,
        rating: 4.7,
        category: 1
      },
      {
        id: 4,
        name: '迪士尼乐园',
        description: '上海迪士尼乐园是中国内地首座迪士尼主题乐园，融合了迪士尼经典元素与中国特色。',
        imageUrl: '/images/spots/disney.jpg',
        price: 399,
        rating: 4.7,
        category: 3
      },
      {
        id: 5,
        name: '长城',
        description: '万里长城是中国古代伟大的防御工程，也是世界文化遗产，象征着中华民族的智慧和力量。',
        imageUrl: '/images/spots/greatwall.jpg',
        price: 40,
        rating: 4.8,
        category: 2
      },
      {
        id: 6,
        name: '南京路步行街',
        description: '上海南京路是中国第一商业街，汇集各类商场、餐厅和特色小店。',
        imageUrl: '/images/spots/nanjingroad.jpg',
        price: 0,
        rating: 4.5,
        category: 4
      },
      {
        id: 7,
        name: '欢乐谷',
        description: '北京欢乐谷是大型现代化主题乐园，以刺激的游乐设施和精彩的表演著称。',
        imageUrl: '/images/spots/happyvalley.jpg',
        price: 299,
        rating: 4.6,
        category: 3
      },
      {
        id: 8,
        name: '泰山',
        description: '泰山是中国五岳之首，以气势磅礴的山势和深厚的文化底蕴闻名。',
        imageUrl: '/images/spots/taishan.jpg',
        price: 125,
        rating: 4.7,
        category: 1
      },
      {
        id: 9,
        name: '天坛',
        description: '北京天坛是明清两代帝王祭天的场所，以精湛的建筑艺术和深远的文化内涵著称。',
        imageUrl: '/images/spots/tiantan.jpg',
        price: 35,
        rating: 4.8,
        category: 2
      },
      {
        id: 10,
        name: '外滩美食街',
        description: '上海外滩美食街汇集各类特色餐厅，既能品尝美食，又能欣赏黄浦江夜景。',
        imageUrl: '/images/spots/bund.jpg',
        price: 0,
        rating: 4.6,
        category: 4
      },
      {
        id: 11,
        name: '商洛康养之都',
        description: '商洛是陕西省著名的康养胜地，融合了秦岭文化与康养特色，自然环境优美，气候宜人。',
        imageUrl: '/images/spots/shangluo.jpg',
        price: 50,
        rating: 4.7,
        category: 2
      }
    ],
    filteredSpots: [], // 用于存储搜索结果
    searchKeyword: '', // 搜索关键词
    isSearching: false, // 是否正在搜索
    currentCategory: null,
    diaries: []
  },

  onLoad: function() {
    // 页面加载时显示所有景点
    this.setData({
      filteredSpots: [],
      isSearching: false,
      currentCategory: null
    });
  },

  // 处理输入变化
  onInputChange: function(e) {
    const keyword = e.detail.value;
    // 只更新关键词，不立即搜索
    this.setData({
      searchKeyword: keyword
    });
  },
  
  onSearch: function() {
    const keyword = this.data.searchKeyword.trim();
    if (keyword) {
      const filteredSpots = this.data.spots.filter(spot => {
        return spot.name.includes(keyword) || spot.description.includes(keyword);
      });
      this.setData({
        isSearching: true,
        filteredSpots: filteredSpots
      });
      if (filteredSpots.length > 0) {
        wx.showToast({
          title: `找到${filteredSpots.length}个景点`,
          icon: 'none'
        });
      }
    } else {
      this.clearSearch();
    }
  },

  clearSearch: function() {
    this.setData({
      searchKeyword: '',
      isSearching: false,
      filteredSpots: []
    });
  },

  onBannerTap: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  onCategoryTap: function(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id);
    
    if (categoryId === 5) { // 更多分类
      this.setData({
        currentCategory: null,
        isSearching: false
      });
      return;
    }

    this.setData({
      currentCategory: categoryId,
      isSearching: false
    });

    // 显示分类提示
    const categoryName = this.data.categories.find(c => c.id === categoryId).name;
    wx.showToast({
      title: `${categoryName}`,
      icon: 'none'
    });
  },

  onSpotTap: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  async loadDiaries() {
    try {
      // 获取当前用户信息
      const userInfo = wx.getStorageSync('userInfo');
      console.log('当前用户信息:', userInfo);

      if (!userInfo || !userInfo.id) {
        console.log('用户未登录');
        wx.showToast({
          title: '请先登录',
          icon: 'none',
          duration: 2000
        });
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }, 2000);
        return;
      }

      const response = await request('/api/diaries', {
        method: 'GET',
        data: {
          user_id: userInfo.id
        }
      });
      console.log('获取到的日记列表:', response);
      
      if (response.success) {
        const diaries = response.data.map(diary => ({
          ...diary,
          author: diary.nickname || diary.username || '未知用户',
          date: diary.date || diary.created_at.split(' ')[0]
        }));
        console.log('处理后的日记数据:', diaries);
        this.setData({ diaries });
      } else {
        throw new Error(response.message || '获取日记列表失败');
      }
    } catch (error) {
      console.error('获取日记列表失败:', error);
      wx.showToast({
        title: error.message || '获取日记列表失败',
        icon: 'none',
        duration: 2000
      });
    }
  }
});